<?php
class ControllerCommunityLottery extends Controller{
    public function index(){
        $this->language->load('community/lottery');
        $this->language->load('community/community_header');
                
        $this->document->setTitle($this->language->get('heading_title'));
                
        $this->load->model('community/lottery');
        $this->load->model('tool/image');

        //detect if user login
        if($this->customer->isLogged()){
            $this->data['is_user_login']=TRUE;
        }else{
            $this->data['is_user_login']=FALSE;
        }

        $this->data['breadcrumbs']=array();
        
        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('common/home'),
            'text'      =>      $this->language->get('text_home'),
            'separator'=>      FALSE
        );
        
        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/community'),
            'text'      =>      $this->language->get('text_community'),
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['breadcrumbs'][]=array(
            'href'      =>      $this->url->link('community/lottery'),
            'text'      =>      $this->language->get('heading_title'),
            'separator' =>      $this->language->get('text_separator')
        );

        $this->data['text_click_draw']=$this->language->get('text_click_draw');
        $this->data['text_try_again']=$this->language->get('text_try_again');
        $this->data['text_reveal_others']=$this->language->get('text_reveal_others');
        $this->data['text_lottery_help']=sprintf($this->language->get('text_lottery_help'),$this->config->get('lottery_cost'),$this->url->link('community/community'));
        $this->data['text_latest_winners']=$this->language->get('text_latest_winners');
        $this->data['text_win']=$this->language->get('text_win');

        $this->data['tab_lottery']=$this->language->get('tab_lottery');
        $this->data['tab_prize']=$this->language->get('tab_prize');

        $this->data['contact_link']=$this->url->link('information/contact');

        // adding facebook's meta tags for Like button start
        $this->document->addFBMeta('og:title', $this->language->get('lottery_title'));
        $this->document->addFBMeta('og:url', $this->url->link('community/yourday'));
        $this->document->addFBMeta('fb:admins', 'micbus');
        $this->document->addFBMeta('og:type', 'website');
        $this->document->addFBMeta('og:site_name', $this->config->get('config_name'));
        $this->document->addFBMeta('og:image', DIR_IMAGE . 'others/your_day_thumb.jpg');

        $this->data['lottery_title']=$this->language->get('lottery_title');
        $this->data['snslink']=$this->url->link('community/yourday');

        //prize
        $this->data['prizes']=array();

        foreach($this->config->get('lottery') as $key => $value){
            $prize='';

            switch($value['prize']){
                case 0:
                    $prize=sprintf($this->language->get('text_prize_coupon'),$value['item']);
                    break;
                case -1:
                    $prize=sprintf($this->language->get('text_prize_reward_point'),$value['item']);
                    break;
                case -2:
                    $prize=$this->language->get('text_no_prize');
                    break;
                default:
                    $product_data=$this->model_community_lottery->getProductData($value['prize']);
                    $product_images=$this->model_community_lottery->getProductImages($value['prize']);

                    $image_str='';

                    foreach($product_images as $product_image){
                        $image_str.='<a class="popup' . $key . '" style="display:none;" rel="popup' . $key . '" href="' . $this->model_tool_image->resize($product_image['image'], 500, 500) . '"><img src="' . $this->model_tool_image->resize($product_data['image'], 1, 1) . '" alt="' . $product_data['name'] . '" /></a>';
                    }

                    $prize='<a href="' . $this->url->link('product/product', 'product_id=' . $value['prize']) . '" target="_blank">' . $product_data['name'] . '</a>' . '<br /><br /><a class="popup' . $key . '" rel="popup' . $key . '" href="' . $this->model_tool_image->resize($product_data['image'], 500, 500) . '"><img src="' . $this->model_tool_image->resize($product_data['image'], 200, 200) . '" alt="' . $product_data['name'] . '" /></a>' . $image_str;
            }

            switch($value['id']){
                case 1:
                    $id=$this->language->get('text_first_prize');
                    break;
                case 2:
                    $id=$this->language->get('text_second_prize');
                    break;
                case 3:
                    $id=$this->language->get('text_third_prize');
                    break;
                case 4:
                    $id=$this->language->get('text_forth_prize');
                    break;
                case 5:
                    $id=$this->language->get('text_fifth_prize');
                    break;
                case 6:
                    $id=$this->language->get('text_sixth_prize');
                    break;
                case 7:
                    $id=$this->language->get('text_seventh_prize');
                    break;
                case 8:
                    $id=$this->language->get('text_eighth_prize');
                    break;
            }

            if($key==8){
                break;
            }

            $this->data['prizes'][$key]=array(
                'id'        =>      $id,
                'prize'     =>      $prize,
            );
        }

        //latest winners
        $this->data['winners']=array();

        $results=$this->model_community_lottery->getLatestLotteryWinners();

        foreach($results as $result){
            $this->data['winners'][]=array(
                'user_name'  =>     $result['username'],
                'user_link'  =>     $this->url->link('community/profile', 'uid=' .  $result['user_id']),
                'prize'      =>     $result['prize_code']>0 ? '<a href="' . $this->url->link('product/product', 'product_id=' .  $result['prize_code']) . '">' . $result['prize_name'] . '</a>' : ($result['prize_code']==0 ? sprintf($this->language->get('text_winner_coupon'),$result['prize_name']) :  sprintf($this->language->get('text_winner_reward_point'),$result['prize_name']))
            );
        }

        if(file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/community/lottery.tpl')){
            $this->template=$this->config->get('config_template') . '/template/community/lottery.tpl';
		}else{
            $this->template='default/template/community/lottery.tpl';
		}	
			
        $this->children = array(
            'common/column_left',
			'common/column_right',
			'common/content_top',
			'common/content_bottom',
			'common/footer',
			'common/header',
			'community/community_header'
		);
		
		$this->response->setOutput($this->render()); 	
  	}

    public function result(){
        $this->language->load('community/lottery');
        $this->load->model('community/lottery');

        $now_time=time();
        $json=array();

        if($this->customer->getForumPoints()<$this->config->get('lottery_cost')){
            $json['error'] = $this->language->get('error_insufficient_points');
        }

        if(isset($this->request->cookie['lottery_draw']) && $this->request->cookie['lottery_draw']>=2){
            $json['error'] = $this->language->get('error_max_draw');
        }

        if(!isset($this->request->cookie['lottery_draw'])){
            //detect draw records
            $histories=$this->model_community_lottery->getLotteryHistory();

            $draw_record=0;

            foreach($histories AS $history){
                if($history['draw_time']+60*60*24>=$now_time){
                    $draw_record++;
                }
            }

            if($draw_record>=2){
                $json['error'] = $this->language->get('error_max_draw');
            }
        }

        if(!$this->customer->isLogged()){
            $json['error'] = $this->language->get('error_not_logged');
        }

        if($this->customer->getMasterSlave()=='sl'){
            $json['error'] = sprintf($this->language->get('error_slave_account'),$this->url->link('account/forum_point'));
        }

        if (!isset($json['error'])) {
            if(!isset($this->session->data['lottery_draw'])){
                $this->session->data['lottery_draw']=0;
            }

            $lottery_setting=$this->config->get('lottery');
            $prize_arr=array();

            foreach($lottery_setting as $key => $value){
                $prize='';

                switch($value['prize']){
                    case 0:
                        $prize=sprintf($this->language->get('text_prize_coupon'),$value['item']);
                        break;
                    case -1:
                        $prize=sprintf($this->language->get('text_prize_reward_point'),$value['item']);
                        break;
                    case -2:
                        $prize=$this->language->get('text_no_prize');
                        break;
                    default:
                        $product_data=$this->model_community_lottery->getProductData($value['prize']);

                        $prize=$product_data['name'];
                }

                $prize_arr[$key]=array(
                    'id'        =>      $value['id'],
                    'prize'     =>      $prize,
                    'v'         =>      $value['v'],
                    'type'      =>      $value['prize']
                );
            }

            $arr=array();

            foreach ($prize_arr as $key => $val) {
                $arr[$val['id']] = $val['v'];
            }

            $rid = $this->getRand($arr); //根据概率获取奖项id
            $json['success']['yes'] = $prize_arr[$rid-1]['prize']; //中奖项

            switch($prize_arr[$rid-1]['type']){
                case -2:
                    $json['success']['text'] = $this->language->get('text_no_prize_info');
                    break;
                case -1:
                    $json['success']['text'] = sprintf($this->language->get('text_reward_point_info'),$prize_arr[$rid-1]['prize'], $this->url->link('account/reward', '', 'SSL'));
                    break;
                case 0:
                    $json['success']['text'] = sprintf($this->language->get('text_coupon_info'),$prize_arr[$rid-1]['prize'], $this->url->link('account/coupon', '', 'SSL'));
                    break;
                default:
                    $json['success']['text'] = sprintf($this->language->get('text_product_info'), $prize_arr[$rid-1]['prize'], $this->url->link('account/order', '', 'SSL'));
            }

            unset($prize_arr[$rid-1]); //将中奖项从数组中剔除，剩下未中奖项
            shuffle($prize_arr); //打乱数组顺序
            for($i=0;$i<count($prize_arr);$i++){
                $pr[] = $prize_arr[$i]['prize'];
            }
            $json['success']['no'] = $pr;

            switch($rid){
                case 1:
                case 2:
                case 3:
                    $this->model_community_lottery->addLotteryWonProduct($lottery_setting[$rid-1]);
                    break;
                case 4:
                case 5:
                case 6:
                    $this->model_community_lottery->addLotteryWonCoupon($lottery_setting[$rid-1]);
                    break;
                case 7:
                case 8:
                    $this->model_community_lottery->addLotteryWonRewardPoint($lottery_setting[$rid-1]);
                    break;
            }

            $this->model_community_lottery->addLotteryHistoryReducePoints($lottery_setting[$rid-1],$now_time);

            $this->session->data['lottery_draw']++;

            if($this->session->data['lottery_draw']==2){
                setcookie('lottery_draw',$this->session->data['lottery_draw'],$now_time+60*60*24);
            }

            if($this->session->data['lottery_draw']>=2){
                unset($this->session->data['lottery_draw']);
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    private function getRand($proArr) {
        $result = '';

        //概率数组的总概率精度
        $proSum = array_sum($proArr);

        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }
}
?>